package chen.web.controller.forum;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import chen.web.message.Message;
import chen.web.message.MessageManager;
import chen.web.user.Account;
import chen.web.user.AccountManager;


public class MessageController {

	private @Autowired AccountManager am;
	private @Autowired MessageManager mm;
	
	//发送消息页面
	@RequestMapping(value="/message", method=RequestMethod.GET)
	public String _sendMessage(@RequestParam(required=false) Integer receiverId, Model model){
		if(receiverId != null){
			model.addAttribute("receiver", am.getAccount(receiverId));
		}
		return "center/send-message";
	}
	
	//发送消息
	@RequestMapping(value="/message", method=RequestMethod.POST)
	public @ResponseBody JSONResponse sendMessage(@RequestParam String receiverName, @RequestParam String content){
		Account receiver = am.getAccountByName(receiverName.trim());
		Message message = new Message(receiver, content);
		mm.send(message);
		return JSONResponse.successed();
	}
	
	//查看消息
	@RequestMapping(value="/message/{id}", method=RequestMethod.GET)
	public String sendMessage(@PathVariable int id, Model model){
		Message message = mm.getMessage(id);
		List<Message> records = mm.getRecord(message.getReceiver(), message.getSender(), message.getSendTime(), 0, 10);
		model.addAttribute("message", message);
		model.addAttribute("records", records);
		return "center/message";
	}

}
